# -*- coding:utf-8 -*-

"""共通性的与用户相关的功能
"""

from tornado import gen

import settings
from commonlib import timetool, config
from appcommon.appinstance import mongo_mtd_pool, mongo_user_power_pool, mysql_mtd_pool, mysql_mtd_pay_pool


@gen.coroutine
def check_token(request_handler):
    """
    检测用户本次的Access_Token是否有效
    :param request_handler: request对象请求
    :return:{'code':'','msg':''}
    """
    para_dict = request_handler.request.arguments
    user_id = int(para_dict['user_id'][0])
    access_token = para_dict['access_token'][0]
    product_type = int(para_dict['product_type'][0])

    # collection = get_collection(settings.MONGO_MTD_DBNAME, settings.MONGO_MTD_DEVICE_COLLECTION)
    collection = mongo_mtd_pool.get_collection(settings.MONGO_MTD_DBNAME, settings.MONGO_MTD_DEVICE_COLLECTION)

    result = yield collection.find_one(
        {
            'userid': user_id,
            'accesstoken': access_token,
            'producttype': product_type
        },
        {'_id': 0, 'ExpireDate': 1})

    if result:
        if result['ExpireDate'] >= timetool.get_timestamp():
            raise gen.Return({"code": "0", "msg": u"ok"})
        else:
            if user_id in settings.WHITE_USER_ID_LIST:
                raise gen.Return({"code": "0", "msg": u"ok"})
            else:
                raise gen.Return({"code": "1012", "msg": config.CODE1012})
    else:

        if user_id in settings.WHITE_USER_ID_LIST:
            raise gen.Return({"code": "0", "msg": u"ok"})
        else:
            raise gen.Return({"code": "1011", "msg": config.CODE1011})


@gen.coroutine
def get_username_with_userid(user_id, product_type):
    """
    根据用户ID获取用户的名称
    :param user_id:用户ID
    :param product_type:产品类型
    :return:
    """
    # db_collection = get_collection(settings.MONGO_MTD_DBNAME, settings.MONGO_MTD_DEVICE_COLLECTION)
    db_collection = mongo_mtd_pool.get_collection(settings.MONGO_MTD_DBNAME, settings.MONGO_MTD_DEVICE_COLLECTION)

    user_info = yield db_collection.find_one(
        {'userid': user_id, 'producttype': product_type},
        {'userid': 1, 'username': 1, 'devicetoken': '1', '_id': 0})

    raise gen.Return(user_info)


@gen.coroutine
def get_classids_with_username(username, search_date=None):
    """
    根据用户名从mongodb中查出对应的classId列表【短讯】
    :param username:用户名
    :param search_date:用户查询数据的日期，获取用户权限时，以用户查询的日期做为判定条件
    :return:
    """

    # db_nms_user = get_collection(settings.MONGO_MTD_DBNAME, settings.MONGO_MTD_NMSUSER_COLLECTION)
    db_nms_user = mongo_mtd_pool.get_collection(settings.MONGO_MTD_DBNAME, settings.MONGO_MTD_NMSUSER_COLLECTION)
    if search_date:
        end_stamp = timetool.convert_date_to_timestamp(search_date + ' 00:00:00')
    else:
        end_stamp = timetool.get_timestamp_of_before_day(0, 0)
    cursor = db_nms_user.find({'username': username, 'endtime': {'$gte': end_stamp}}, {'classid': 1})
    result = []

    for user in (yield cursor.to_list(length=500)):
        result.append(user['classid'])

    raise gen.Return(result)


@gen.coroutine
def get_class_with_username(username, search_date=None):
    """
    根据用户名从mongodb中查出对应的classId列表【短讯】
    :param username:
    :param search_date:用户查询数据的日期，获取用户权限时，以用户查询的日期做为判定条件
    :return:
    """
    # db_nms_user = get_collection(settings.MONGO_MTD_DBNAME, settings.MONGO_MTD_NMSUSER_COLLECTION)
    db_nms_user = mongo_mtd_pool.get_collection(settings.MONGO_MTD_DBNAME, settings.MONGO_MTD_NMSUSER_COLLECTION)

    if search_date:
        end_stamp = timetool.convert_date_to_timestamp(search_date + ' 00:00:00')
    else:
        end_stamp = timetool.get_timestamp_of_before_day(0, 0)

    cursor = db_nms_user.find(
        {'username': username, 'endtime': {'$gte': end_stamp}},
        {'classid': 1, 'classname': 1, '_id': 0})

    result = yield cursor.to_list(length=500)
    raise gen.Return(result)


@gen.coroutine
def get_user_powers_of_mobile(user_id, power_type=258):
    """
    根据用户ID和power_type获取已订阅的未过期的产品权限【客户端】
    :param user_id:用户ID
    :param power_type:258 客户端权限  281:价格库权限
    :return:
    """
    # db_power_class = get_collection(settings.MONGO_POWER_DBNAME, settings.MONGO_POWER_CLASS_COLLECTION)
    db_power_class = mongo_user_power_pool.get_collection(settings.MONGO_POWER_DBNAME,
                                                          settings.MONGO_POWER_CLASS_COLLECTION)
    cursor = db_power_class.find({
        'userid': user_id,
        'powertype': power_type,
        'date': {'$gte': timetool.get_timestamp()}}, {'_id': 0, 'classid': 1, 'classname': 1})
    power_class = yield cursor.to_list(length=500)
    raise gen.Return(power_class)


@gen.coroutine
def get_user_groupids_of_mobile(user_id):
    """
    根据用户ID获取所有未过期有合同项【客户端】
    :param user_id:用户ID
    :return:
    """
    # db_power_group = get_collection(settings.MONGO_POWER_DBNAME, settings.MONGO_POWER_GROUP_COLLECTION)
    db_power_group = mongo_user_power_pool.get_collection(settings.MONGO_POWER_DBNAME,
                                                          settings.MONGO_POWER_GROUP_COLLECTION)
    con_dict = {'userid': user_id, 'powertype': 258, 'date': {'$gte': timetool.get_timestamp()}}
    cursor = db_power_group.find(con_dict, {'_id': 0, 'groupid': 1})
    power_group = yield cursor.to_list(length=500)
    raise gen.Return(power_group)


@gen.coroutine
def get_news_info(newskey):
    """
    根据newskey到News_Mobile表中获取信息基本属性[免费,所属网,产品,栏目]
    :param newskey:News_Mobile中的newskey
    :return:
    """
    search_sql = (
        "SELECT newsid,classid,siteid,columnid,pubtime,title,BIN(free) AS free,sccid  "
        "FROM News_Mobile WHERE NewsKey = {newskey} "
    )
    # news_info_res = yield get_data_from_info_db(
    #     search_sql.format(newskey=newskey), search_type="one")

    news_info_res = yield mysql_mtd_pool.get_one(search_sql.format(newskey=newskey))
    raise gen.Return(news_info_res)


@gen.coroutine
def get_property_of_news(newskey):
    """
    根据newskey到News_Mobile表中获取信息基本属性[免费,所属网,产品,栏目]及sccid对应的[FClassName,FColumnName,FreedDays]
    :param newskey:News_Mobile中的newskey
    :return:
    """
    search_sql = (
        "SELECT "
        "news.newsid,news.classid,news.siteid,news.columnid,news.pubtime,news.title,BIN(news.free) AS free,news.sccid, "
        "news.sccid,rccs.FClassName,rccs.FColumnName,rccs.FreedDays "
        "FROM News_Mobile as news "
        "LEFT JOIN Real_Column_Class_Site AS rccs  "
        "ON news.sccid = rccs.sccid "
        "WHERE NewsKey = {newskey} "
    )

    news_info_res = yield mysql_mtd_pool.get_one(search_sql.format(newskey=newskey))
    raise gen.Return(news_info_res)


@gen.coroutine
def get_real_column_class_info(sccid):
    """
    根据sccid获取产品栏目对应关系的相关属性
    :param sccid:
    :return:
    """
    search_sql = (
        "SELECT FClassName,FColumnName,FreedDays FROM Real_Column_Class_Site WHERE sccid = {sccid} "
    )
    # news_info_res = yield get_data_from_info_db(
    #     search_sql.format(sccid=sccid), search_type="one")

    news_info_res = yield mysql_mtd_pool.get_one(search_sql.format(sccid=sccid))
    raise gen.Return(news_info_res)


@gen.coroutine
def check_user_power_of_mobile(sccid, user_id, class_id):
    """
    根据userid分别利用sccid,classid在power_group，power_class中判断是否有权限
    :param sccid:
    :param user_id:
    :param class_id:
    :return:
    """
    search_sql = (
        "SELECT GroupId FROM Rela_PowerGroup WHERE sccid = {sccid} "
    )

    # gid_res = yield get_data_from_info_db(
    #     search_sql.format(sccid=sccid))

    gid_res = yield mysql_mtd_pool.get_all(
        search_sql.format(sccid=sccid))

    groupid_list = [item[0] for item in gid_res]

    if groupid_list:
        con_dict = {
            'userid': user_id, 'powertype': 258,
            'groupid': {'$in': groupid_list},
            'date': {'$gte': timetool.get_timestamp()}
        }
        # db_power_group = get_collection(settings.MONGO_POWER_DBNAME, settings.MONGO_POWER_GROUP_COLLECTION)
        db_power_group = mongo_user_power_pool.get_collection(settings.MONGO_POWER_DBNAME,
                                                              settings.MONGO_POWER_GROUP_COLLECTION)
        result = yield db_power_group.find_one(con_dict, {'_id': 0, 'groupid': 1})
        if result:
            raise gen.Return(True)
        else:
            raise gen.Return(False)
    else:
        # db_power_class = get_collection(settings.MONGO_POWER_DBNAME, settings.MONGO_POWER_CLASS_COLLECTION)
        db_power_class = mongo_user_power_pool.get_collection(settings.MONGO_POWER_DBNAME,
                                                              settings.MONGO_POWER_CLASS_COLLECTION)
        con_dict = {
            'userid': user_id,
            'powertype': 258,
            'classid': class_id,
            'date': {'$gte': timetool.get_timestamp()}
        }
        result = yield db_power_class.find_one(con_dict, {'_id': 0, 'classid': 1, 'classname': 1})
        if result:
            raise gen.Return(True)
        else:
            raise gen.Return(False)


def check_param(request_handler):
    """
    根据info_type判断在不同情况下查询时指定的参数是否存在
    :param request_handler:
    :return:
    """
    query_key_list = request_handler.request.arguments.keys()
    info_type = int(request_handler.get_argument('info_type', '1'))

    check_res = {}
    if info_type == 1:
        check_res['code'] = "0"
        check_res['msg'] = u""
    elif info_type == 2:
        # site_id,class_id,值的类型会在verify_check的进行校验,所在这只判断参数是否有就可以,下面的sccid也是类似
        if 'site_id' in query_key_list \
                and 'class_id' in query_key_list \
                and 'user_id' in query_key_list \
                and 'access_token' in query_key_list:
            check_res['code'] = "0"
            check_res['msg'] = u""
        else:
            check_res['code'] = "1002"
            check_res['msg'] = config.CODE1002
    elif info_type == 3:
        if 'sccid' in query_key_list and 'user_id' in query_key_list and 'access_token' in query_key_list:
            check_res['code'] = "0"
            check_res['msg'] = u""
        else:
            check_res['code'] = "1002"
            check_res['msg'] = config.CODE1002
    elif info_type == 7:
        if 'user_id' in query_key_list and 'access_token' in query_key_list:
            check_res['code'] = "0"
            check_res['msg'] = u""
        else:
            check_res['code'] = "1002"
            check_res['msg'] = config.CODE1002
    elif info_type == 8:
        check_res['code'] = "0"
        check_res['msg'] = u""
    else:
        check_res['code'] = "1002"
        check_res['msg'] = config.CODE1002

    return check_res


@gen.coroutine
def get_goods_status_from_shopping_cat(user_id):
    """
    获取指定用户购物车中所选产品的状态[获取的状态是以当前为基本15天之内的]
    :param user_id:
    :return:
    """
    start_datetime = timetool.get_date_time_of_before_day(15, label=0)
    end_datetime = timetool.get_current_datetime()
    # search_sql = (
    #     "SELECT  "
    #     "CONCAT(state,'-', CAST(selected AS CHAR)) AS goods_status, GROUP_CONCAT(pid) AS pids  "
    #     "FROM cart_products  "
    #     "WHERE belong_user = {user_id} "
    #     "AND state <> 'paid' "
    #     "GROUP BY state,selected "
    # )

    # submitted 状态的订单只取最近15天的
    search_sql = (
        "SELECT  "
        "CONCAT(state,'-', CAST(selected AS CHAR)) AS goods_status, GROUP_CONCAT(pid) AS pids  "
        "FROM cart_products  "
        "WHERE belong_user = {user_id} "
        "AND (state = 'added' OR (state = 'submitted' AND submitted_time BETWEEN '{start_datetime}' and '{end_datetime}')) "
        # "AND state <> 'paid' "
        # "AND submitted_time between '{start_datetime}' and '{end_datetime}'  "
        "GROUP BY state,selected "
    )

    # print 'get_goods_status_from_shopping_cat sql:',search_sql.format(user_id=user_id,
    #                                                                   start_datetime=start_datetime,
    #                                                                   end_datetime=end_datetime)

    news_info_res = yield mysql_mtd_pay_pool.get_all(search_sql.format(user_id=user_id,
                                                                       start_datetime=start_datetime,
                                                                       end_datetime=end_datetime),
                                                     cursor='dict')
    raise gen.Return(news_info_res)


@gen.coroutine
def get_pdu_num_from_shopping_cat(user_id, state='added'):
    """
    获取用户购物车中指定状态商品的总数
    :param user_id:
    :return:
    """
    search_sql = (
        "SELECT COUNT(1) AS pdu_num FROM cart_products  "
        "WHERE belong_user = {user_id} "
        "And state IN ('{state}') "
    )
    # print search_sql.format(user_id=user_id, state=state)
    news_info_res = yield mysql_mtd_pay_pool.get_one(search_sql.format(user_id=user_id, state=state), cursor='dict')
    raise gen.Return(news_info_res)


@gen.coroutine
def check_status_of_pid(user_id, pid, order_type='trial', state='paid'):
    """
    获取用户指定pid,指定状态的订单
    :param user_id:
    :param pid:
    :param order_type:
    :param state:
    :return:
    """
    search_sql = (
        "SELECT COUNT(1) AS result FROM cart_products   "
        "WHERE belong_user = {user_id} "
        "And pid={pid} "
        "AND order_type='{order_type}'"
        "And state ='{state}' "
    )
    # print search_sql.format(user_id=user_id, state=state)
    news_info_res = yield mysql_mtd_pay_pool.get_one(search_sql.format(
        user_id=user_id, pid=pid, order_type=order_type, state=state), cursor='dict')
    raise gen.Return(news_info_res)


@gen.coroutine
def check_status_of_pid_with_token(user_id, pid, order_type='trial', state='paid', device_token=''):
    """
    获取用户指定pid,指定状态的订单
    :param user_id:
    :param pid:
    :param order_type:
    :param state:
    :param device_token:
    :return:
    """
    search_sql = (
        "SELECT COUNT(1) AS result FROM cart_products   "
        "WHERE pid={pid} "
        "AND order_type='{order_type}'"
        "And state ='{state}' "
        "And device_token ='{device_token}' "
    )
    # print search_sql.format(user_id=user_id, state=state)
    news_info_res = yield mysql_mtd_pay_pool.get_one(search_sql.format(
        user_id=user_id, pid=pid, order_type=order_type, state=state, device_token=device_token), cursor='dict')
    raise gen.Return(news_info_res)
